<template>
  <div class="answer-page-container">
    <!-- 搜索区域 -->
    <div class="search-card">
      <a-form
        :model="formSearchParams"
        layout="inline"
        @submit="doSearch"
        class="compact-search-form"
      >
        <a-form-item field="resultName" label="结果名称">
          <a-input
            v-model="formSearchParams.resultName"
            placeholder="请输入结果名称"
            allow-clear
            class="search-input"
          />
        </a-form-item>

        <a-form-item field="resultDesc" label="结果描述">
          <a-input
            v-model="formSearchParams.resultDesc"
            placeholder="请输入结果描述"
            allow-clear
            class="search-input"
          />
        </a-form-item>

        <a-form-item field="appId" label="应用ID">
          <a-input
            v-model="formSearchParams.appId"
            placeholder="请输入应用ID"
            allow-clear
            class="search-input"
          />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit" class="search-btn">
            <template #icon>
              <icon-search />
            </template>
            搜索
          </a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-card">
      <a-table
        :columns="columns"
        :data="dataList"
        :pagination="pagination"
        :row-class="setRowClass"
        @page-change="onPageChange"
        row-key="id"
        bordered
      >
        <!-- 结果图片 -->
        <template #resultPicture="{ record }">
          <a-image
            width="64"
            :src="record.resultPicture"
            :preview="!!record.resultPicture"
            fallback="/placeholder-image.png"
          />
        </template>

        <!-- 应用类型标签 -->
        <template #appType="{ record }">
          <a-tag color="arcoblue" size="small">
            {{ APP_TYPE_MAP[record.appType] }}
          </a-tag>
        </template>

        <!-- 评分策略标签 -->
        <template #scoringStrategy="{ record }">
          <a-tag color="purple" size="small">
            {{ APP_SCORING_STRATEGY_MAP[record.scoringStrategy] }}
          </a-tag>
        </template>

        <!-- 优化后的choices列 -->
        <template #choices="{ record }">
          <a-tooltip
            :content="formatChoices(record.choices)"
            position="top"
            mini
            :disabled="!record.choices"
          >
            <div class="truncate-text">
              {{ formatChoices(record.choices) || "-" }}
            </div>
          </a-tooltip>
        </template>

        <!-- 新增结果描述的省略处理 -->
        <template #resultDesc="{ record }">
          <a-tooltip
            :content="record.resultDesc"
            position="top"
            mini
            :disabled="!record.resultDesc"
          >
            <div class="truncate-text">
              {{ record.resultDesc || "-" }}
            </div>
          </a-tooltip>
        </template>
        <!-- 时间格式化 -->
        <template #createTime="{ record }">
          {{ dayjs(record.createTime).format("YYYY-MM-DD") }}
        </template>

        <template #updateTime="{ record }">
          {{ dayjs(record.updateTime).format("YYYY-MM-DD") }}
        </template>

        <!-- 操作列 -->
        <template #optional="{ record }">
          <a-space :size="12">
            <a-button
              type="outline"
              :href="`/answer/result/${record.id}`"
              size="small"
            >
              查看详情
            </a-button>
            <a-popconfirm
              content="确定要删除该记录吗？"
              type="error"
              @ok="doDelete(record)"
            >
              <a-button status="danger" size="small">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watchEffect } from "vue";
import {
  deleteUserAnswerUsingPost,
  listMyUserAnswerVoByPageUsingPost,
} from "@/api/userAnswerController";
import { API } from "@/api/typings";
import message from "@arco-design/web-vue/es/message";
import { dayjs } from "@arco-design/web-vue/es/_utils/date";
import { APP_SCORING_STRATEGY_MAP, APP_TYPE_MAP } from "@/constant/app";

const formSearchParams = ref<API.UserAnswerQueryRequest>({});

// 初始化搜索条件（不应该被修改）
const initSearchParams = {
  current: 1,
  pageSize: 10,
};

const searchParams = ref<API.UserAnswerQueryRequest>({
  ...initSearchParams,
});
const dataList = ref<API.UserAnswerVO[]>([]);
const total = ref<number>(0);
// 分页配置
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50],
});

// 分页变化处理
const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

// 新增行样式方法
const setRowClass = (record: API.UserAnswerVO, index: number) => {
  return index % 2 === 1 ? "stripe-row" : "";
};
/**
 * 加载数据
 */
const loadData = async () => {
  const res = await listMyUserAnswerVoByPageUsingPost(searchParams.value);
  if (res.data.code === 0) {
    dataList.value = res.data.data?.records || [];
    total.value = res.data.data?.total || 0;
  } else {
    message.error("获取数据失败，" + res.data.message);
  }
};
// 优化后的choices格式化方法
const formatChoices = (choices) => {
  if (!choices) return "";
  try {
    const parsed = JSON.parse(choices);
    if (Array.isArray(parsed)) {
      return parsed.join(", ");
    }
    return JSON.stringify(parsed);
  } catch {
    return choices;
  }
};

/**
 * 执行搜索
 */
const doSearch = () => {
  searchParams.value = {
    ...initSearchParams,
    ...formSearchParams.value,
  };
};

/**
 * 删除
 * @param record
 */
const doDelete = async (record: API.UserAnswer) => {
  if (!record.id) {
    return;
  }

  const res = await deleteUserAnswerUsingPost({
    id: record.id,
  });
  if (res.data.code === 0) {
    loadData();
  } else {
    message.error("删除失败，" + res.data.message);
  }
};

/**
 * 监听 searchParams 变量，改变时触发数据的重新加载
 */
watchEffect(() => {
  loadData();
});

// 表格列配置
const columns = [
  {
    title: "选项",
    dataIndex: "choices",
    width: 100,
  },
  {
    title: "名称",
    dataIndex: "resultName",
  },
  {
    title: "描述",
    dataIndex: "resultDesc",
    slotName: "resultDesc",
    width: 200,
  },
  {
    title: "图片",
    dataIndex: "resultPicture",
    slotName: "resultPicture",
  },
  {
    title: "得分",
    dataIndex: "resultScore",
  },
  {
    title: "应用名",
    dataIndex: "appName",
  },
  {
    title: "应用类型",
    dataIndex: "appType",
    slotName: "appType",
  },
  {
    title: "评分策略",
    dataIndex: "scoringStrategy",
    slotName: "scoringStrategy",
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    slotName: "createTime",
  },
  {
    title: "操作",
    slotName: "optional",
  },
];
</script>

<style scoped>
.answer-page-container {
  padding: 16px;
  background-color: var(--color-fill-1);
  height: 100%;
  box-sizing: border-box;
}

.search-card {
  margin-bottom: 16px;
  padding: 16px;
  background: var(--color-bg-2);
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.compact-search-form {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.compact-search-form .arco-form-item {
  margin-bottom: 0;
}

.search-input {
  width: 200px;
}

.search-btn {
  border-radius: 4px;
  padding: 0 16px;
}

.table-card {
  background: var(--color-bg-2);
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}
/* 新增省略样式 */
.truncate-text {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .truncate-text {
    max-width: 120px;
  }
}
.table-card :deep(.arco-table-tr) {
  transition: background-color 0.2s;
}

.table-card :deep(.arco-table-tr:hover) {
  background-color: var(--color-fill-1) !important;
}

.table-card :deep(.stripe-row) {
  background-color: var(--color-fill-1);
}

.table-card :deep(.arco-table-th) {
  background-color: var(--color-fill-1);
  font-weight: 500;
}

@media (max-width: 768px) {
  .search-input {
    width: 160px;
  }

  .table-card {
    overflow-x: auto;
  }
}
</style>
